from django.shortcuts import render
from django.views import View
from django.http import JsonResponse, HttpResponseBadRequest
import json
from apps.goods.models import SKU
import base64, pickle
from django_redis import get_redis_connection
# Create your views here.

class UserEsayCartsView(View):
    def get(self, request):
        '''购物车的简单展示'''
        user = request.user
        if user.is_authenticated:
            # redis
            # 拿到数据
            redis_conn = get_redis_connection('carts')
            sku_dict = redis_conn.hgetall('cartsb_%s' % user.id)
            cart_skus = []
            for sku_id, count in sku_dict.items():
                print(sku_id, type(sku_id))
                sku = SKU.objects.get(id=sku_id)
                cart_skus.append({
                    "id": int(sku_id),
                    "name": sku.name,
                    "count": int(count),
                    "default_image_url": sku.default_image.url
                })
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_skus': cart_skus,
            })


        else:
            # cooki
            sku_cookie = request.COOKIES.get('cartsb')
            sku_dict = pickle.loads(base64.b64decode(sku_cookie.encode()))
            cart_skus = []
            for sku_id, count_dict in sku_dict.items():
                count = count_dict['count']
                sku = SKU.objects.get(id=sku_id)
                cart_skus.append({
                    "id": int(sku_id),
                    "name": sku.name,
                    "count": int(count),
                    "default_image_url": sku.default_image.url

                })
            return JsonResponse({
                    'code': 0,
                    'errmsg': 'ok',
                    'cart_skus': cart_skus,
                })

# ===========================================================================================================
class UserAllChoiceView(View):
    def put(self, request):
        '''商品全选'''
        user = request.user
        selected_data = json.loads(request.body.decode())
        selected = selected_data.get('selected')
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')

            sku_info = redis_conn.hgetall('cartsb_%s' % user.id)
            sku_ids = sku_info.keys()
            if selected:
                redis_conn.sadd('selectedb_%s' % user.id, *sku_ids)
            else:
                redis_conn.srem('selectedb_%s' % user.id, *sku_ids)
            return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
        else:
            sku_cookie = request.COOKIES.get('cartsb')
            sku_dict = pickle.loads(base64.b64decode(sku_cookie.encode()))
            if selected:
                sku_ids = sku_dict.keys()
                for sku_id in sku_ids:
                    sku_dict[sku_id]['selected'] = selected

            return JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})

# =========================================================================================================
class UserCartsView(View):
    def delete(self, request):
        '''删除购物车'''
        sku_data = json.loads(request.body.decode())
        sku_id = sku_data.get('sku_id')
        user = request.user
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')
            redis_conn.hdel('cartsb_%s' % user.id, sku_id)
            redis_conn.srem('selectedb_%s' % user.id, sku_id)

            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})

        else:
            sku_cookie = request.COOKIES.get('cartsb')
            sku_dict = pickle.loads(base64.b64decode(sku_cookie.encode()))
            del sku_dict[sku_id]
            # 删除结束后，没有响应的数据，只需要响应状态码即可
            return JsonResponse({'code': 0, 'errmsg': '删除购物车成功'})

    def put(self, request):
        '''修改购物车'''
        user = request.user
        data_dict = json.loads(request.body.decode())
        sku_id = data_dict.get('sku_id')
        count = data_dict.get('count')
        selected = data_dict.get('selected')
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hset('cartsb_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selectedb_%s' % user.id, sku_id)
            else:
                pl.srem('selectedb_%s' % user.id, sku_id)

            pl.execute()

            # 创建响应对象
            sku = SKU.objects.get(id=sku_id)
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return JsonResponse({'code': 0, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        else:
            # cookie
            sku_data = request.COOKIES.get('carts')
            # 解码
            sku_dict = pickle.loads(base64.b64decode(sku_data.encode()))

            sku_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            print(sku_dict)

            # 加密
            sku_cookies = base64.b64encode(pickle.dumps(sku_dict)).decode()

            sku = SKU.objects.get(id=sku_id)
            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            response = JsonResponse({'code': 0, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
            # 响应结果并将购物车数据写入到cookie
            response.set_cookie('cartsb', sku_cookies, max_age=7 * 24 * 3600)
            return response



    def get(self, request):
        '''展示购物车'''
        user = request.user
        if user.is_authenticated:
            # redis
            redis_conn = get_redis_connection('carts')

            sku_dict = redis_conn.hgetall('cartsb_%s' % user.id) # 返回dict

            print(sku_dict)

            cart_selectedb = redis_conn.smembers('selectedb_%s' % user.id)

            skus = {}
            for sku_id, count in sku_dict.items():
                sku_id = eval(sku_id)
                count = eval(count)
                sku_b = str(sku_id).encode('utf-8')
                skus[sku_id] = {

                    'count': count,
                    'selected': sku_b in cart_selectedb
                }
                '''skus = {1:{'count': 1, 'selected': True}}'''

            print(type(sku_id))


        else:
            # cookie
            skus_cookie = request.COOKIES.get('cartsb')
            # 解码
            skus = pickle.loads(base64.b64decode(skus_cookie.encode()))


        print(skus)
        sku_ids = [sku_id for sku_id in skus.keys()]
        # 查询数据库获商品list
        try:
            sku_list = SKU.objects.filter(id__in=sku_ids)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('no')

        cart_skus = []
        for sku in sku_list:
            cart_skus.append({
                "id": sku.id,
                "name": sku.name,
                "count": skus[sku.id]['count'],
                "selected": skus[sku.id]['selected'],
                "default_image_url": sku.default_image.url,
                "price": sku.price,
                "amount": sku.price * skus[sku.id]['count']
            })


        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })

    def post(self, request):
        '''添加购物车'''
        # 拿到参数
        user = request.user
        sku_dict = json.loads(request.body.decode())
        sku_id = sku_dict.get('sku_id')
        count = sku_dict.get('count')
        selected = sku_dict.get('selected')

        # 效验参数

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest('no')

        if user.is_authenticated:
            # 添加到redis
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            pl.hincrby('cartsb_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('selectedb_%s' % user.id, sku_id)
            pl.execute()
            return JsonResponse({'code': 0, 'errmsg': 'ok'})



        else:
            # cookies
            sku_cookie = request.COOKIES.get('cartsb')
            if sku_cookie:
                # 解码
                sku_dict = pickle.loads(base64.b64decode(sku_cookie.encode()))
                '''{16:{'conut': 2, 'selected': None}}'''
                sku_dict[sku_id] = {'count': count, 'selected': selected}
            else:
                sku_dict = {sku_id: {'count': count, 'selected': selected}}


            # 加密
            sku_b = base64.b64encode(pickle.dumps(sku_dict)).decode()

            respose = JsonResponse({'code': 0, 'errmsg': 'ok'})

            respose.set_cookie('cartsb', sku_b, max_age=7 * 24 * 3600)

            return respose





